<?php
/**
 * hook钩子触发短信发送
 */
namespace app\api\hook;
include_once ROOT_PATH.'vendor/alibabacloud/client/src/Functions.php';
include_once ROOT_PATH.'vendor/alibabacloud/client/autoload.php';
include_once ROOT_PATH.'vendor/clagiordano/weblibs-configmanager/src/ConfigManager.php';

//阿里云短信发送相关类 composer安装
//composer require alibabacloud/sdk
use Swoft\Task\Bean\Annotation\Task;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;


class SmsNotice
{

    function smsNotice($sms)
    {
        $param = ['hour'=>$sms['msg']];
        return $this->sendMsg($sms['mobile'],$sms['template'],$param);
    }

    /*function smsCheck($sms)
    {
    	return $this->sendMsg($sms->mobile,['code'=>$sms->code],'code');
    }*/


    //@mobile 手机号码
    //@param  短信发送参数
    //@template 短信发送模板编号key值
    private function sendMsg($mobile,$TemplateCode,$param){

        $config = \config('alisms');

        if(!isset($config)||empty($config)){
            return false;
        }
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessSecret'])
            ->regionId($config['regionId'])
            ->asGlobalClient();

        $query = [
            'PhoneNumbers' => $mobile,
            'SignName' => $config['SignName'],
            'TemplateCode' => $TemplateCode,
            //'TemplateParam' => json_encode($param)
        ];
        if ($param['hour']){
            $query['TemplateParam'] = json_encode($param);
        }
        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => $query
                ])
                ->request();

            if($result->Code=="OK"){
                return true;
            }else{
                return false;
            }
        } catch (ClientException $e) {
            return false;
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            return false;
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

}